<template>
  <div class="mineinfo">
    <div class="account">
      <div class="editBtn">
        <span>基础信息</span>
        <button @click="updateInfo" v-if="status === false">编辑</button>
        <button @click="submitForm('ruleForm')" v-preventReClick v-else>
          提交
        </button>
      </div>
      <div class="content" v-show="status === false">
        <el-form :model="msgInfo" label-width="100px" class="demo-ruleForm">
          <el-form-item label="姓名：">
            <span>{{ msgInfo.name }}</span>
            <!-- <el-input v-model="ruleForm.name" style="width:400px" ></el-input> -->
          </el-form-item>
          <el-form-item label="昵称：">
            <!-- <el-input v-model="ruleForm.nick"  style="width:400px"></el-input> -->
            <span>{{ msgInfo.nick }}</span>
          </el-form-item>
          <el-form-item label="头像：" style="height: 40px">
            <img :src="msgInfo.url" alt="" style="width: 40px" />
          </el-form-item>
          <el-form-item label="手机号：">
            <!-- <el-input v-model="ruleForm.telephone" style="width:400px"></el-input> -->
            <span>{{ msgInfo.telephone }}</span>
          </el-form-item>
          <el-form-item label="QQ号：">
            <!-- <el-input placeholder="请输入QQ号"
            v-model="ruleForm.qq" style="width:400px"></el-input> -->
            <span>{{ msgInfo.qq }}</span>
          </el-form-item>
        </el-form>
      </div>
      <div class="content trueStatus" v-show="status === true">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- 如果是学生不能修改姓名 -->
          <el-form-item label="姓名:" prop="name" v-if="userType === 4">
            <el-input
              v-model="ruleForm.name"
              style="width: 400px"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名:" prop="name" v-else>
            <el-input v-model="ruleForm.name" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="昵称：">
            <el-input v-model="ruleForm.nick" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="头像：" style="height: 40px; line-height: 0">
            <el-upload
              class="avatar-uploader"
              action="http://test.zhihanyixing.com:8084/file/upload"
              :show-file-list="false"
              :headers="{ token: token }"
              :data="{ userId: userid }"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="ruleForm.url" :src="ruleForm.url" class="avatar" />
              <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
              <span
                v-else
                style="font-size: 12px; line-height: none; color: #999"
                >点击更换头像</span
              >
            </el-upload>
          </el-form-item>
          <el-form-item label="手机号：" prop="telephone">
            <el-input
              v-model="ruleForm.telephone"
              style="width: 400px"
              type="number"
            ></el-input>
          </el-form-item>
          <el-form-item label="QQ号：">
            <el-input
              placeholder="请输入QQ号"
              v-model="ruleForm.qq"
              style="width: 400px"
              type="number"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="password">
      <div class="editBtn">
        <span>修改密码</span>
      </div>
      <div class="content">
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="formName"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="旧密码：" prop="oldPwd">
            <el-input
              type="password"
              v-model="ruleForm.oldPwd"
              autocomplete="off"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item label="新密码：" prop="pass">
            <el-input
              type="password"
              v-model="ruleForm.pass"
              autocomplete="off"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码：" prop="checkPass">
            <el-input
              type="password"
              v-model="ruleForm.checkPass"
              autocomplete="off"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <div class="Btn">
              <el-button
                type="primary"
                @click="submitPwd('formName')"
                v-preventReClick
                >提交</el-button
              >
              <!-- <el-button @click="resetForm('formName')">重置输入</el-button> -->
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserMsg, editUser, updatePwd } from '../../api/systemManage/user';
import index from '../../components/header/index.vue';
import { mapActions } from 'vuex';
export default {
  components: { index },
  name: 'mineinfo',
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      promptMsg: {
        name: '',
        nick: '',
        avatar: '',
        telephone1: '',
        qq: '',
        pwd: ''
      },
      status: false,
      pwdStatus: false,
      userid: '',
      msgInfo: {},
      ruleForm: {
        name: '',
        pass: '',
        checkPass: '',
        nick: '',
        telephone: '',
        qq: '',
        url: '',
        oldPwd: ''
      },
      urlImg: '',
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 13, message: '长度在 2 到 13 个字符', trigger: 'change' }
        ],
        pass: [
          { validator: validatePass, trigger: 'blur' },
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' },
          { required: true, message: '请再次输入新密码', trigger: 'blur' }
        ],
        oldPwd: [{ required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        telephone: [
          { min: 11, max: 11, message: '长度在 11 个字符', trigger: 'change' }
        ]

      },
      token: '',
      userType: '',
      imgStatus: false
    };
  },
  methods: {
    ...mapActions(['getUserInfoAsync']),
    // 点击修改信息
    updateInfo() {
      this.status = true;
    },
    // 提交修改基本资料
    submitForm(ruleForm) {
      this.$refs[ruleForm].validate(async (valid) => {
        if (valid) {
          // alert('submit!');
          // console.log(this.ruleForm);
          if (this.ruleForm.name !== '' || this.ruleForm.name !== null) {
            let data = { name: this.ruleForm.name, nick: this.ruleForm.nick, avatar: this.ruleForm.url, telephone1: this.ruleForm.telephone, qq: this.ruleForm.qq, id: Number(sessionStorage.getItem('userid')) };
            console.log(data);
            const res = await editUser(JSON.stringify(data));
            console.log(res);
            if (res.code === 200) {
              this.$message({
                message: '修改成功！',
                type: 'success'
              });
              this.status = false;
              // 重新调用获取用户的接口更改header区域用户的信息
              this.getUserInfoAsync({ id: sessionStorage.getItem('userid') });
              this.getUser();
            } else {
              this.$message.error('修改失败');
            }
          } else {
            this.$message({
              showClose: true,
              message: '提交失败，个人名称不能为空!',
              type: 'error'
            });
          }
        } else {
          this.$message({
            showClose: true,
            message: '提交失败，请正确填写信息!',
            type: 'error'
          });
          // console.log('修改失败，请正确填写信息!');
          return false;
        }
      });
      // this.status = false;
    },
    // 获取用户信息
    async getUser() {
      console.log(sessionStorage.getItem('userid'));
      const res = await getUserMsg({ id: sessionStorage.getItem('userid') });
      console.log('获取用户信息', res);
      this.msgInfo = res.data;
      this.ruleForm.name = res.data.name;
      this.ruleForm.nick = res.data.nick;
      this.ruleForm.url = res.data.url;
      this.ruleForm.telephone = res.data.telephone;
      this.ruleForm.qq = res.data.qq;
      // this.ruleForm.name = res.data.name;
    },
    // 取消修改
    cancel() {
      this.ruleForm = {};
      this.status = false;
      this.getUser();
    },
    // 文件上传
    handleAvatarSuccess(res, file) {
      console.log(res);
      this.ruleForm.url = res.data.url;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 修改密码
    submitPwd(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 定义一个变量保存要修改的密码信息
          const data = { id: sessionStorage.getItem('userid'), pwd: this.ruleForm.checkPass };
          if (this.ruleForm.oldPwd !== this.msgInfo.pwd) {
            this.$message({
              showClose: true,
              message: '修改失败，旧密码输入错误',
              type: 'error'
            });
          } else {
            const res = await updatePwd(JSON.stringify(data));
            console.log(res);
            if (res.code === 200) {
              this.$message({
                message: '修改成功，请重新登录！',
                type: 'success'
              });
              // 将本地存储的信息，跳转到登录页面
              setTimeout(() => {
                sessionStorage.clear();
                this.$router.replace('/');
              }, 3000);
              // this.getUser();
              // this.status = false;
            } else {
              this.$message.error('修改失败');
            }
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }

  },
  created() {
    this.getUser();
    this.userid = sessionStorage.getItem('userid');
    this.token = sessionStorage.getItem('usertoken');
    this.userType = sessionStorage.getItem('usertype');
  }
};
</script>

<style lang="less" scoped>
.mineinfo {
  padding: 20px 20px;
  .account,
  .password {
    box-shadow: 1px 2px 3px 0px rgba(153, 153, 153, 0.5);
    height: 450px;
    background-color: white;
    .editBtn {
      padding: 20px;
      display: flex;
      justify-content: space-between;
      button {
        width: 100px;
        height: 35px;
        background: #2fc0e0;
        border-radius: 4px;
        color: white;
      }
    }
    .content {
      width: 500px;
      padding-right: 100px;
      // height: 430px;
      margin: 0 auto;
      // margin-right: 100px;
      // margin-left: 500px;
      margin-top: 40px;
      .item {
        font-size: 14px;
        margin-top: 20px;
        text-align: right;
        height: 45px;
        display: flex;
        align-items: center;
        // line-height: 45px;
        .text {
          color: #555555;
          text-align: right;
          display: inline-block;
          width: 100px;
        }
        p {
          margin: 0;
          padding: 0;
          height: 45px;
          box-sizing: border-box;
        }
        .contentVal {
          box-sizing: border-box;
          padding-left: 30px;
          text-align: left;
          display: inline-block;
          color: #333333;
        }
        .img {
          height: 40px;
          width: 40px;
        }
      }
    }
  }
  .password {
    margin-top: 20px;
    .Btn {
      width: 100%;
      display: flex;
      justify-content: space-evenly;
      button {
        width: 115px;
        // padding: 10px 10px;
        height: 40px;
        // background: #E8F8FB;
        border-radius: 4px;
        font-size: 14px;
        // color: #2FC0E0;
        background: #2fc0e0;
        color: #ffffff;
        font-weight: 400;
        border: 0;
        &:nth-child(2) {
          background: #e8f8fb;
          color: #2fc0e0;
        }
      }
    }
  }
}
/deep/.el-input__inner:focus {
  border-color: 0;
  border: 0;
  box-shadow: inset 0 0.005208rem 0.020833rem 0 #2fc0e0,
    inset 0 -0.005208rem 0.020833rem 0 #2fc0e0,
    inset 0.005208rem 0 0.020833rem 0 #2fc0e0,
    inset -0.005208rem 0 0.020833rem 0 #2fc0e0 !important;
}
// 取消input的上下箭头
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
input::-webkit-outer-spin-button {
  -webkit-appearance: none !important;
}
input[type="number"] {
  -moz-appearance: textfield !important;
}

.avatar-uploader.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/.avatar-uploader {
  height: 45px;
  display: inline-block;
}
/deep/.trueStatus .el-form-item__content,
.avatar-uploader-icon {
  height: 45px;
  line-height: normal;
}
/deep/.avatar-uploader-icon {
  height: 45px !important;
  width: 45px !important;
}
/deep/.el-upload--text {
  // width: 200px;
  height: 45px;
  width: 45px;
  // box-shadow: ;
  box-shadow: 1px 2px 3px 0px rgba(153, 153, 153, 0.5);
  // border: 1px dashed #d9d9d9;
  // background: #2FC0E0;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 40px;
  height: 40px;
  display: block;
}
</style>
